#include "records.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QStandardPaths>

#include "../component/ChartWidget.h"
#include "common/ConstData.h"
#include "define.h"
#include "ui_records.h"

records::records(QWidget *parent)
    : QWidget(parent), ui(new Ui::records), chartWidget(nullptr), isChartMode(false)
{
    ui->setupUi(this);
    ui->tb_hour->setText("🕐 小时记录");
    ui->tb_upload->setText("🌐 上传记录");
    ui->tb_error->setText("⚠️ 错误记录");
    ui->tb_calib->setText("📊 校准记录");
    ui->tb_inspect->setText("🔍 核查记录");
    ui->tb_spike_recovery->setText("🧪 加标回收记录");

    // 创建菜单按钮组
    menuButtonGroup = new QButtonGroup(this);
    menuButtonGroup->addButton(ui->tb_hour, 1);
    menuButtonGroup->addButton(ui->tb_upload, 2);
    menuButtonGroup->addButton(ui->tb_error, 3);
    menuButtonGroup->addButton(ui->tb_calib, 4);
    menuButtonGroup->addButton(ui->tb_inspect, 5);
    menuButtonGroup->addButton(ui->tb_spike_recovery, 6);
    connect(menuButtonGroup, &QButtonGroup::idClicked, this, &records::onMenuButtonClicked);

    // 设置表格属性
    ui->tableWidget->setAlternatingRowColors(true);                         // 交替行颜色
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);   // 整行选择
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);  // 单行选择
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);    // 禁止编辑

    // 设置列自动拉伸以填满表格宽度
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);  // 固定第一列
    // 隐藏行号
    ui->tableWidget->verticalHeader()->setVisible(false);

    // 设置行高
    setRowHeightByRecordType(currentRecordType);

    // 计算并设置每页显示的行数
    updatePageSize();

    // 初始化设备下拉框
    initDeviceComboBox();

    // 根据默认记录类型更新设备过滤器显示状态
    updateDeviceFilterVisibility();

    // 初始化图表组件
    chartWidget = new ChartWidget(this);
    // 将图表添加到布局中但初始隐藏
    ui->gridLayout->addWidget(chartWidget, 1, 0, 1, 3);
    chartWidget->setVisible(false);

    // 连接图表组件的返回信号
    connect(chartWidget, &ChartWidget::backToTableRequested, this, &records::onBackToTableClicked);
}

records::~records()
{
    if (chartWidget) {
        delete chartWidget;
    }
    delete ui;
}

void records::onMenuButtonClicked(int id)
{
    // 转换为记录类型
    RecordType newType = static_cast<RecordType>(id);

    // 如果类型没有改变，直接返回
    if (newType == currentRecordType) {
        return;
    }

    // 如果当前在图表模式，先切换回表格模式
    if (isChartMode) {
        showTable();
    }

    // 更新当前记录类型
    currentRecordType = newType;

    // 根据记录类型设置行高
    setRowHeightByRecordType(newType);

    // 根据记录类型控制设备过滤器的显示/隐藏
    updateDeviceFilterVisibility();

    // 重置到第一页
    currentPage = 1;

    // 更新页面信息并重新加载数据
    updatePageSize();
    updatePageInfo();
    loadPageData();
}
void records::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    // 窗口大小改变时重新计算pageSize
    updatePageSize();
    // 重新加载数据
    if (isVisible()) {
        updatePageInfo();
        loadPageData();
    }
}

void records::updatePageSize()
{
    // 获取表格的可视区域高度
    int tableHeight = ui->tableWidget->height();
    // 获取表头高度
    int headerHeight = ui->tableWidget->horizontalHeader()->height();
    // 获取单行高度
    int rowHeight = ui->tableWidget->verticalHeader()->defaultSectionSize();

    // 计算可显示的完整行数
    int visibleRows = (tableHeight - headerHeight) / rowHeight;

    // 设置每页显示行数（至少显示1行）
    pageSize = qMax(1, visibleRows);
}

void records::setRowHeightByRecordType(RecordType type)
{
    int rowHeight = 35;  // 默认行高

    switch (type) {
        case RecordType::DeviceData:
            rowHeight = 35;  // 设备数据记录行高
            break;

        case RecordType::UploadData:
            rowHeight = 65;  // 上传记录行高
            break;

        case RecordType::ErrorData:
            rowHeight = 35;  // 错误记录行高
            break;

        case RecordType::CalibrationData:
            rowHeight = 35;  // 校准记录行高
            break;

        case RecordType::InspectionData:
            rowHeight = 35;  // 核查记录行高
            break;

        case RecordType::SpikeRecoveryData:
            rowHeight = 35;  // 加标回收记录行高
            break;
    }

    // 设置新的行高
    ui->tableWidget->verticalHeader()->setDefaultSectionSize(rowHeight);
    ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);  // 固定行高
}

void records::loadPageData()
{
    // 只在错误记录、校准记录、核查记录和加标回收记录中使用设备过滤
    if (currentRecordType == RecordType::ErrorData ||
        currentRecordType == RecordType::CalibrationData ||
        currentRecordType == RecordType::InspectionData ||
        currentRecordType == RecordType::SpikeRecoveryData) {
        RecordDataHelper::loadPageData(ui->tableWidget, currentRecordType, currentPage, pageSize,
                                       queryDate, queryDeviceName);
    } else {
        RecordDataHelper::loadPageData(ui->tableWidget, currentRecordType, currentPage, pageSize,
                                       queryDate);
    }
}

void records::updatePageInfo()
{
    // 只在错误记录、校准记录、核查记录和加标回收记录中使用设备过滤
    if (currentRecordType == RecordType::ErrorData ||
        currentRecordType == RecordType::CalibrationData ||
        currentRecordType == RecordType::InspectionData ||
        currentRecordType == RecordType::SpikeRecoveryData) {
        totalRecords =
            RecordDataHelper::getTotalRecords(currentRecordType, queryDate, queryDeviceName);
    } else {
        totalRecords = RecordDataHelper::getTotalRecords(currentRecordType, queryDate);
    }

    totalPages = (totalRecords + pageSize - 1) / pageSize;  // 向上取整

    // 确保当前页在有效范围内
    if (currentPage < 1) currentPage = 1;
    if (totalPages == 0) totalPages = 1;  // 避免无数据时除以零
    if (currentPage > totalPages) currentPage = totalPages;

    // 更新按钮状态
    ui->bt_prePage->setEnabled(currentPage > 1);
    ui->bt_nextPage->setEnabled(currentPage < totalPages);
    ui->bt_headPage->setEnabled(currentPage > 1);
    ui->bt_tailPage->setEnabled(currentPage < totalPages);

    // 更新页码显示
    QString pageInfo = QString("%1/%2(%3条)").arg(currentPage).arg(totalPages).arg(totalRecords);
    ui->lb_pageInfo->setText(pageInfo);
}

void records::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);
    updatePageInfo();
    loadPageData();
}

void records::on_bt_prePage_clicked()
{
    if (currentPage > 1) {
        currentPage--;
        loadPageData();
        updatePageInfo();
    }
}

void records::on_bt_nextPage_clicked()
{
    if (currentPage < totalPages) {
        currentPage++;
        loadPageData();
        updatePageInfo();
    }
}

void records::on_bt_headPage_clicked()
{
    if (currentPage != 1) {
        currentPage = 1;
        loadPageData();
        updatePageInfo();
    }
}

void records::on_bt_tailPage_clicked()
{
    if (currentPage != totalPages) {
        currentPage = totalPages;
        loadPageData();
        updatePageInfo();
    }
}

void records::on_bt_export_clicked()
{
    // 根据当前记录类型生成默认文件名
    QString recordTypeName;
    switch (currentRecordType) {
        case RecordType::DeviceData:
            recordTypeName = "设备数据";
            break;
        case RecordType::UploadData:
            recordTypeName = "上传记录";
            break;
        case RecordType::ErrorData:
            recordTypeName = "错误记录";
            break;
        case RecordType::CalibrationData:
            recordTypeName = "校准记录";
            break;
        case RecordType::InspectionData:
            recordTypeName = "核查记录";
            break;
        case RecordType::SpikeRecoveryData:
            recordTypeName = "加标回收记录";
            break;
    }

    // 生成默认文件名：记录类型_日期.csv
    QString defaultFileName = recordTypeName + "_";
    if (queryDate.isValid()) {
        defaultFileName += queryDate.toString("yyyy-MM-dd");
    } else {
        defaultFileName += "全部";
    }
    defaultFileName += ".csv";

    // 获取文档目录作为默认保存位置
    QString documentsPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
    QString defaultFilePath = documentsPath + "/" + defaultFileName;

    // 打开文件保存对话框
    QString filePath = QFileDialog::getSaveFileName(this, "导出数据", defaultFilePath,
                                                    "CSV文件 (*.csv);;所有文件 (*)");

    // 如果用户取消了对话框，直接返回
    if (filePath.isEmpty()) {
        return;
    }

    // 确保文件扩展名为.csv
    if (!filePath.endsWith(".csv", Qt::CaseInsensitive)) {
        filePath += ".csv";
    }

    // 执行导出
    bool success =
        RecordDataHelper::exportToCSV(filePath, currentRecordType, queryDate, queryDeviceName);

    if (success) {
        showSuccess(QString("数据已成功导出到：\n%1").arg(filePath));
    } else {
        showError("系统", QString("数据导出失败：\n%1").arg(filePath));
    }
}

void records::on_bt_exec_clicked()
{
    // 获取用户在界面上选择的日期
    queryDate = ui->dateEdit->date();

    // 重置到第一页
    currentPage = 1;

    // 更新页面信息并加载数据
    updatePageInfo();
    loadPageData();
}

void records::on_bt_purge_clicked()
{
    // 重置到第一页
    currentPage = 1;
    queryDate = QDate();                // 重置日期查询条件为无效日期，即查询所有记录
    queryDeviceName = QString();        // 重置设备名称查询条件为空字符串，即查询所有设备
    ui->cb_device->setCurrentIndex(0);  // 重置设备选择框到"全部设备"
    // 更新页面信息并加载数据
    updatePageInfo();
    loadPageData();
}

void records::on_cb_device_currentTextChanged(const QString &text)
{
    // 如果选择的是"全部设备"，则设置queryDeviceName为空字符串
    if (text == "全部设备") {
        queryDeviceName = QString();
    } else {
        queryDeviceName = text;
    }

    // 重置到第一页
    currentPage = 1;

    // 更新页面信息并加载数据
    updatePageInfo();
    loadPageData();
}

void records::initDeviceComboBox()
{
    // 从ConstData获取设备名称列表
    for (const QString &deviceName : DEVICE_NAMES) {
        ui->cb_device->addItem(deviceName);
    }

    // 设置默认选中"全部设备"
    ui->cb_device->setCurrentIndex(0);
}

void records::updateDeviceFilterVisibility()
{
    // 只在错误记录、校准记录、核查记录和加标回收记录页面显示设备过滤器
    bool shouldShow = (currentRecordType == RecordType::ErrorData ||
                       currentRecordType == RecordType::CalibrationData ||
                       currentRecordType == RecordType::InspectionData ||
                       currentRecordType == RecordType::SpikeRecoveryData);

    ui->label_device->setVisible(shouldShow);
    ui->cb_device->setVisible(shouldShow);

    // 只在小时记录页面（设备数据）显示图表按钮
    bool shouldShowChart = (currentRecordType == RecordType::DeviceData);
    ui->bt_chart->setVisible(shouldShowChart);

    // 如果隐藏设备过滤器，重置查询条件
    if (!shouldShow) {
        queryDeviceName = QString();
        ui->cb_device->setCurrentIndex(0);  // 重置到"全部设备"
    }
}

void records::on_bt_chart_clicked() { showChart(); }

void records::onBackToTableClicked() { showTable(); }

void records::showChart()
{
    // 只在小时记录（设备数据）模式下显示图表
    if (currentRecordType == RecordType::DeviceData && !isChartMode) {
        isChartMode = true;
        ui->tableWidget->setVisible(false);
        chartWidget->setVisible(true);

        // 隐藏分页和查询控件
        ui->widget_2->setVisible(false);
    }
}

void records::showTable()
{
    if (isChartMode) {
        isChartMode = false;
        ui->tableWidget->setVisible(true);
        chartWidget->setVisible(false);

        // 显示分页和查询控件
        ui->widget_2->setVisible(true);

        // 重新加载数据
        updatePageInfo();
        loadPageData();
    }
}